<template>
    <!--  外框架-->
    <div class="framework1">
        <!--      内框架-->
        <div class="framework2" v-if="!clickTemplate">
            <div class="top-class-table">
                <div class="header">
                    <div style="margin-left: 10px;font-weight: bold">门前五包->检查记录</div>
                </div>
                <!--      按钮行-->
                <div class="button_group">
                    <el-input v-model="searchName" placeholder="单位名称/人员姓名"
                              style="width: 250px;margin-left: 15px;" clearable></el-input>
                    <el-input v-model="searchCard" placeholder="信用代码或营业执照号/身份证号"
                              style="width: 250px;margin-left: 15px;margin-right: 15px" clearable></el-input>
                    <el-select style="margin-right: 10px" v-model="searchIsPlace" placeholder="选择单位或个人" clearable>
                        <el-option label="单位" value="0"/>
                        <el-option label="个人" value="1"/>
                    </el-select>
                    <!-- 状态下拉框 -->
                    <el-select style="margin-right: 15px" v-model="status" placeholder="请选择状态" clearable>
                        <el-option label="商户提交" value="0" />
                        <el-option label="待审查" value="1" />
                        <el-option label="待审核" value="2" />
                        <el-option label="待审批" value="3" />
                        <el-option label="已通过" value="4" />
                        <el-option label="已驳回" value="5" />
                    </el-select>
                    <el-button type="primary" icon="Search" @click="getFrontFiveBagsData()">搜索</el-button>
                </div>

                <!--      表格-->
                <div style="height: calc(100vh - 134px)">
                    <el-table :data="frontFiveBagsData" :row-style="{ height: '47px' }"
                        style="width: 100%;height:calc(100% - 68px)" :header-cell-style="{ background: '#f4f3f9' }">
                        <el-table-column prop="companyName" label="单位名称/人员姓名" align="center"/>
                        <el-table-column prop="companyLicense" label="信用代码或营业执照号/身份证号" align="center"/>
                        <el-table-column prop="telephone" label="联系方式" align="center"/>
                        <el-table-column prop="problem" label="处理的问题" align="center" />
                        <el-table-column prop="problemTime" label="发现问题时间" align="center" />
                        <el-table-column prop="createDate" label="提交日期" align="center" />
                        <el-table-column prop="status" label="状态" align="center">
                            <template #default="scope">
                                {{ getStatusString(scope.row.status) }}
                            </template>
                        </el-table-column>
                        <el-table-column fixed="right" label="操作" width="200" align="center">
                            <template #default="scope">
                                <el-button type="primary" size="small" icon="Edit"
                                    @click="clickTemplateTable(scope.row)">查看</el-button>
                                <el-button type="success" v-if="scope.row.status === '0' && permissionIsShow.sign"
                                    size="small" icon="check" @click="updateStatus(scope.row, '1')">完成签名</el-button>
                                <el-button type="success" v-if="scope.row.status === '1' && permissionIsShow.passOne"
                                    size="small" icon="check" @click="updateStatus(scope.row, '2')">审查</el-button>
                                <el-button type="success" v-if="scope.row.status === '2' && permissionIsShow.passTwo"
                                    size="small" icon="check" @click="updateStatus(scope.row, '3')">审核</el-button>
                                <el-button type="success" v-if="scope.row.status === '3' && permissionIsShow.passThree"
                                    size="small" icon="check" @click="updateStatus(scope.row, '4')">审批</el-button>
                                <el-button type="danger"
                                    v-if="scope.row.status !== '4' && scope.row.status !== '5' && permissionIsShow.reject"
                                    size="small" icon="close" @click="Reject(scope.row)">驳回</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <!--        页数导航栏-->
                    <div class="footer">
                        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                            :page-sizes="[5, 10]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
                            :total="total">
                        </el-pagination>
                    </div>
                </div>
            </div>
        </div>
        <div class="framework2" v-else>
            <div class="templateHeader">
                <span style="padding-bottom: 4px;">检查记录</span>
                <span style="float: right;padding-bottom: 6px;">
                    <el-button type="danger" icon="Close" size="small" @click="closeTemplate()">
                    </el-button>
                </span>
            </div>
            <!-- 这里打开五包项目的检查记录详情页，role为1表示可以进行执法人员签名 -->
            <iframe class="iframe-container" ref="iframe"
                :src="iframeOrigin + '/inspection?id=' + selectOption.id + '&role=' + viewType"></iframe>

        </div>
        <el-dialog title="驳回" v-model="dialogVisible" width="30%">
            <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
                <el-form-item label="驳回原因" prop="rejectionReason">
                    <el-input v-model="form.rejectionReason" type="textarea"
                        :autosize="{ minRows: 2, maxRows: 4 }"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button type="primary" @click="submitReject">确定</el-button>
                <el-button @click="closeReject">取消</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script>
import request from "@/utils/request";
import { fiveBagsIp } from '@/ipConfig/fiveBagsConfig';


export default {
    name: 'Place',
    components: {
        fiveBagsIp,
    },
    data() {
        return {
            searchName: '', // 单位名称/人员姓名检索
            searchCard: '', //营业执照/身份证号检索
            searchIsPlace: '', //是否单位
            status: '', // 状态检索
            frontFiveBagsData: [],
            total: 0,
            currentPage: 1,
            pageSize: 10,
            clickTemplate: false, //查看
            selectOption: {},
            iframeOrigin: fiveBagsIp,
            dialogVisible: false,
            form: {
                id: '',
                status: 5,
                params: {},
                rejectionReason: '',
            },
            rules: {
                rejectionReason: [{ required: true, message: '请输入驳回原因', trigger: 'blur' }]
            },
            viewType: '', //判断查看五包项目的功能（1：可以执法人员签名 2：只能下载）
            // 登录用户信息
            loginUserInfo: {
                id: '',
                responsibleScope: '', //查询范围
                roleLevel: '', //角色等级
                unitId: '', //内设部门ID
                userRole: '', //角色ID
                permissions: [], // 按钮路径（数据库中的path）
            },
            // 按钮权限
            permissionIsShow: {
                sign: false,
                passOne: false,
                passTwo: false,
                passThree: false,
                reject: false,
            },
        }
    },
    created() {
        const info = JSON.parse(localStorage.getItem("user"));
        this.loginUserInfo = {
            id: Number(info.id),
            responsibleScope: info.responsibleScope, //查询范围
            roleLevel: Number(info.roleLevel),
            unitId: Number(info.unitId),
            userRole: Number(info.userRole),
            permissions: info.permissions.filter(item => Number(item.menuId) === 39).map(item => item.path),
        }
        this.permissionIsShow = {
            sign: this.loginUserInfo.permissions.includes('frontFiveBags-sign'),
            passOne: this.loginUserInfo.permissions.includes('frontFiveBags-passOne'),
            passTwo: this.loginUserInfo.permissions.includes('frontFiveBags-passTwo'),
            passThree: this.loginUserInfo.permissions.includes('frontFiveBags-passThree'),
            reject: this.loginUserInfo.permissions.includes('frontFiveBags-reject'),
        }
    },

    mounted() {
        this.getFrontFiveBagsData();
        // 注册消息监听，接收iframe发送的消息
        window.addEventListener('message', this.handleIframeMessage);
    },

    beforeUnmount() {
        // 组件销毁时移除监听，防止内存泄漏
        window.removeEventListener('message', this.handleIframeMessage);
    },

    methods: {
        // 处理iframe发送的消息
        handleIframeMessage(event) {
            const iframeOrigin = this.iframeOrigin;
            if (event.origin !== iframeOrigin) {
                return; // 来源非法，忽略消息
            }
            const message = event.data;
            if (message.action === 'closeDialog') {
                this.closeTemplate(); // 调用关闭方法
            }
        },
        getFrontFiveBagsData() {
            request.get("/front-five-bags/page", {
                params: {
                    pageNum: this.currentPage,
                    pageSize: this.pageSize,
                    status: this.status,
                    name: this.searchName,
                    card: this.searchCard,
                    isPlace: this.searchIsPlace,
                }
            }).then(res => {
                if (res.code === '200') {
                    this.frontFiveBagsData = res.data.records;
                    this.total = res.data.total;
                }
            })
        },
        // 分页
        handleSizeChange(val) {
            this.pageSize = val;
            this.getFrontFiveBagsData();
        },
        handleCurrentChange(val) {
            this.currentPage = val;
            this.getFrontFiveBagsData();
        },

        // 状态返回字符串
        getStatusString(status) {
            switch (status) {
                case '0':
                    return '商户提交';
                case '1':
                    return '待审查';
                case '2':
                    return '待审核';
                case '3':
                    return '待审批';
                case '4':
                    return '已通过';
                case '5':
                    return '已驳回';
                default:
                    return '未知状态';
            }
        },
        // 查看
        clickTemplateTable(row) {
            this.clickTemplate = true;
            this.selectOption = row;
            if (row.status === '0') {
                this.viewType = '1'
            } else {
                this.viewType = '2'
            }
        },
        // 关闭
        closeTemplate() {
            this.clickTemplate = false;
        },
        // 通过函数
        updateStatus(row, status) {
            let statusText = '点击'
            switch (status) {
                case '1':
                    statusText = '完成签名';
                    break;
                case '2':
                    statusText = '审查';
                    break;
                case '3':
                    statusText = '审核';
                    break;
                case '4':
                    statusText = '审批';
                    break;
            }
            this.$confirm('确定要' + statusText + '吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                request.post("/front-five-bags/edit", {
                    id: row.id,
                    status: status,
                }).then(res => {
                    if (res.code === '200') {
                        this.$message({
                            message: '操作成功',
                            type: 'success',
                        });
                        this.getFrontFiveBagsData();
                    }
                })
            }).catch(() => {
                this.$message({
                    message: '操作已取消',
                    type: 'info',
                });
            });
        },
        // 驳回
        Reject(row) {
            this.form.id = row.id
            this.form.params = JSON.parse(row.params)
            this.dialogVisible = true
        },
        submitReject() {
            this.$refs.formRef.validate((valid) => {
                this.form.params.cheaker1 = ''
                this.form.params.cheaker2 = ''
                this.form.params = JSON.stringify(this.form.params)
                if (valid) {
                    request.post("/front-five-bags/edit", this.form).then(res => {
                        if (res.code === '200') {
                            this.$message({
                                message: '操作成功',
                                type: 'success',
                            });
                            this.getFrontFiveBagsData();
                            this.closeReject()
                        }
                    })
                } else {
                    this.$message({
                        message: '请输入驳回原因',
                        type: 'warning',
                    });
                }
            })
        },
        closeReject() {
            this.form = {
                id: '',
                status: 5,
                params: {},
                rejectionReason: '',
            }
            this.dialogVisible = false
        }
    },
}

</script>
<style scoped>
#roleSpan {
    color: black;
    text-decoration: none;
}

/*   外框架   */
.framework1 {
    height: calc(100vh - 88px);
    width: calc(100vh - 200px);
    margin-left: 8px;
    border: solid 1px #D3D3D3;
}

/*   内框架   */
.framework2 {
    height: calc(100vh - 92px);
    border: solid 1px #D3D3D3;
}

/*   表格大标题   */
.header {
    font-size: 16px;
    font-weight: bold;
    padding: 4px 20px;
    background-color: #D3D3D3;
}

/*   表格按键组   */
.button_group {
    padding: 4px 10px;
    background-color: #DDDDDD;
}

/*   表格分页处   */
.footer {
    padding: 4px 10px;
    background-color: #f4f3f9;
}

.el-dialog-image {
    height: 100px;
    width: 200px;
    margin-top: 10px;
    margin-right: 10px;
    border: 1px solid #ccc;
    display: flex;
    align-items: center;
    justify-content: center;
}

/*   文书标题   */
.templateHeader {
    font-size: 19px;
    font-weight: bold;
    padding: 4px 20px;
    height: 30px;
    border: 1px solid #CCCCCC;
    background-color: #E0ECFF;
}

.iframe-container {
    width: 100%;

    height: calc(100% - 40px);
    border: none;
}
</style>
